package com.javacv.plus.extensions.image.steps;

import com.javacv.plus.core.processor.ProcessorContext;
import com.javacv.plus.core.processor.ProcessorStep;
import com.javacv.plus.extensions.image.ImageProcessor;
import com.javacv.plus.extensions.image.ProcessorResult;
import lombok.extern.slf4j.Slf4j;
import org.bytedeco.opencv.opencv_core.Mat;
import org.bytedeco.opencv.opencv_core.Rect;

/**
 * 图像裁剪步骤
 */
@Slf4j
public class CropStep implements ProcessorStep<ImageProcessor, ProcessorResult> {
    private final int x, y, width, height;

    public CropStep(int x, int y, int width, int height) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
    }

    @Override
    public ProcessorResult execute(ImageProcessor processor, ProcessorContext context) throws Exception {
        Mat currentImage = context.getAttribute("currentImage");
        if (currentImage == null) {
            throw new IllegalStateException("当前图像为空");
        }

        log.debug("裁剪图像: x={}, y={}, width={}, height={}", x, y, width, height);

        // 检查裁剪区域是否有效
        if (x < 0 || y < 0 || x + width > currentImage.cols() || y + height > currentImage.rows()) {
            throw new IllegalArgumentException("裁剪区域超出图像边界");
        }

        Rect cropRect = new Rect(x, y, width, height);
        Mat croppedImage = new Mat(currentImage, cropRect);

        context.setAttribute("currentImage", croppedImage);
        context.setAttribute("processedImage", croppedImage);

        log.debug("图像裁剪完成");
        return null;
    }

    @Override
    public String getStepName() {
        return "Crop";
    }

    @Override
    public int getPriority() {
        return 30;
    }
} 